<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Fenxiaoe extends AbstractApi
{

    /**
     * 分销e获取加密的数据
     *
     * @param array $info
     * @param string $secret_key
     * @return false|string
     */
    public function opensslMessage(array $info, string $secret_key): bool|string
    {
        return encryptWithOpenssl( json_encode($info,JSON_UNESCAPED_UNICODE ), $secret_key);
    }

    /**
     * @param array $array
     * @param string $key
     * @return string
     */
    public function sign(array $array, string $key): string
    {
        ksort($array);
        $signStr = 'app_id='.$array['app_id'].'&channel='.$array['channel'].
            '&format='.$array['format']. '&message='.$array['message']. '&method='.$array['method'].
            '&msgtype='.$array['msgtype']. '&request_id='.$array['request_id']. '&timestamp='.$array['timestamp'].
            '&version='.$array['version'];
        $publicKey = openssl_get_privatekey($key);
        openssl_sign($signStr, $sign, $publicKey);
        // openssl_free_key($publicKey);
        return bin2hex($sign);
    }

    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $str = '/^[a-zA-Z]|_[a-zA-Z\d_-]{5,19}$/';
        // 正则
        if (preg_match($str, $bean->getAccount())) {
            $charge_account_type = 'WECHAT';
        } else {
            $eg = '/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0-3,5-8])|(18[0-9])|166|198|199|191|195)\d{8}$/';
            if(preg_match($eg, $bean->getAccount())){
                $charge_account_type = 'MOBILE';
            }else{
                $charge_account_type = 'QQ';
            }
        }
        $info = [
            'app_order_no'      => $bean->getOrderNo(),//订单号
            'goods_sku'         => $bean->getGoodsId(), //商品编码
            'goods_count'       => $bean->getRechargeNum() * $bean->getStartCharging(),
            'charge_query_info' => [
                'charge_account_os_type'    => '',
                'charge_account_type'       => $charge_account_type,
                'charge_account_number'     => $bean->getAccount(),
                'charge_type'               => 0,
            ],
            'notify_url'        => $bean->getNotifyUrl(), //异步回调地址
        ];
        $array = [
            'msgtype'   => 'request_msg',
            'format'    => 'json',
            'version'   => '1.0',
            'app_id'    => $bean->getSupplierNum(),
            'timestamp' => millisecondTimestamp(),
            'method'    => 'order.charge.query',
            'channel'   => 'wap',
            'request_id'=> date('YmdHis').time().rand(0000,9999),
            'message'   => $this->opensslMessage($info, $bean->getSecretKey()),
        ];
        $array['sign'] = $this->sign($array, $bean->getPrivateKey());

        return $array;
    }

    /**
     * TODO 还没好 麻烦死 先跳过
     *
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('state', '');
        $order_sn = $request->input('sellerid', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['2', '4']))->setRechargeSuccess($status == '2');
    }
}
